package by.hatton.engine.service;

import java.util.ArrayList;
import java.util.List;

import by.hatton.engine.bo.BaseRequestDataWrapper;
import by.hatton.engine.utill.RequestCallbackListener;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;

public abstract class BaseServiceHelper {

	private static final String EXTRA_REQUEST_DATA = "rdw";
	private static long idCounter;
	private ResultReceiver mResultReceiver;
	private Context mContext;
	private List<RequestCallbackListener> mListenerStorage;

	public BaseServiceHelper(Context context) {
		mContext = context;
		idCounter = 0;
		mListenerStorage = new ArrayList<RequestCallbackListener>();
		mResultReceiver = new ResultReceiver(new Handler()) {
			@Override
			protected void onReceiveResult(int resultCode, Bundle resultData) {
				onCallback(resultCode, resultData);
			}
		};
	}

	public void addRequestCallbackListener(RequestCallbackListener listener) {
		mListenerStorage.add(listener);
	}

	public void removeRequestCallbackListener(RequestCallbackListener listener) {
		mListenerStorage.remove(listener);
	}

	public long sendRequest(int id){
		long requestId = createRequestId();
		BaseRequestDataWrapper requestWrapper = new BaseRequestDataWrapper();
		requestWrapper.setRequestId(requestId);
		requestWrapper.setRequestSpecificData(prepareSpecificRequestData(id));
		requestWrapper.setResultReceiver(mResultReceiver);
		Intent intent = new Intent(mContext, BaseProcessorService.class).putExtra(EXTRA_REQUEST_DATA, requestWrapper.getData());		
		startService(intent);
		return id;
	}

	protected abstract Bundle prepareSpecificRequestData(int id);
	protected abstract void makeNotification(int statusCode, Bundle data);
	
	private static long createRequestId() {
		return ++idCounter;
	}

	private void onCallback(int statusCode, Bundle data) {
		if (!mListenerStorage.isEmpty() && mListenerStorage != null) {
			for (RequestCallbackListener listener : mListenerStorage) {
				listener.onCallback(statusCode, data);
			}
		} else {
			makeNotification(statusCode, data);
		}
	}

	private void startService(Intent intent) {
		mContext.startService(intent);
	}
}